import { createClientTokenAuthentication } from 'alova/client';
import { createAlova } from 'alova';
import { useUserStore } from '@/stores/user';
import adapterFetch from 'alova/fetch';
import VueHook from 'alova/vue';
import router from '@/router';
import { ElMessage } from 'element-plus';

const userStore = useUserStore();

const { onAuthRequired, onResponseRefreshToken } = createClientTokenAuthentication({
  // ...
});

const alovaInstance = createAlova({
    statesHook: VueHook,
    requestAdapter: adapterFetch(),

    // 请求前
    beforeRequest: onAuthRequired(method => {
        // 设置baseUrl
        method.baseURL = '/wsite';
        // token
        method.config.headers.sk = 'sk ' + userStore.sk;

        // 时间戳禁用浏览器缓存
        method.config.params = {...method.config.params, _t: new Date().getTime()}

    }),

    // 响应后
    responded: {
        // 请求成功
        onSuccess: async (response, method) => {
            const json = await response.json();
            console.log('json.code: ', json.code)

            if (json.code == 200) {
                return json;
            }

            // 未登录
            if (json.code == 1001) {
                ElMessage.error(json.msg)
                ElMessage.error('未登录或登录过期, 请重新登录')
                router.replace({ path: '/login?redirect=' + encodeURIComponent(location.href) })
                throw new Error(json.msg);
            }

            ElMessage.error(json.msg)
            throw new Error(json.msg);
        },
        // 请求失败
        onError: (error, method) => {
            console.error(error)
            console.error(method)
            ElMessage.error(`请求失败, f12请查看控制台异常信息: [${error}]`)
            throw new Error(error);
        }
    }
});

export default alovaInstance;